local extension = Package("rfenghou_hell")
extension.extensionName = "aaa_fenghou"

local U = require "packages/utility/utility"

Fk:loadTranslationTable{
  ["rfenghou_hell"] = "阴间",
}

local luxun = General:new(extension, "rfenghou__hell_luxun", "wu", 4)
--luxun.hidden = true

local qianshi = fk.CreateTriggerSkill{
  name = "rfenghou__qianshi",
  anim_type = "drawcard",
  events = {fk.BeforeCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      for _, move in ipairs(data) do
        if move.from == player.id and move.moveReason == fk.ReasonDiscard and move.proposer == player.id then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
              return true
            end
          end
        end
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local ids = {}
    for _, move in ipairs(data) do
      if move.from == player.id and move.moveReason == fk.ReasonDiscard and move.proposer == player.id then
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
            table.insert(ids, info.cardId)
          end
        end
      end
    end
    if #ids > 0 then
      local cards = room:askForCard(player, #ids, #ids, true, self.name, true, nil, "#rfenghou__qianshi-invoke:::"..#ids)
      if #cards > 0 then
        self.cost_data = {cards = cards}
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local ids = {}
    for _, move in ipairs(data) do
      if move.from == player.id and move.moveReason == fk.ReasonDiscard and move.proposer == player.id then
        local new_info = {}
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
            table.insertIfNeed(ids, info.cardId)
          else
            table.insert(new_info, info)
          end
          if #ids > 0 then
            move.moveInfo = new_info
          end
        end
      end
    end
    room:sendLog{
      type = "#cancelDismantle",
      card = ids,
      arg = self.name,
    }
    room:recastCard(self.cost_data.cards, player, self.name)
    if player.dead then return end
    local use = room:askForUseCard(player, self.name, "slash",
      "#rfenghou__qianshi-slash", true, {bypass_times = true, extraUse = true})
    if use then
      room:useCard(use)
    end
    if player.dead then return end
    if not use or not use.damageDealt then
      local n = #self.cost_data.cards
      local cards = room:askForCard(player, n, n, true, self.name, true, nil, "#rfenghou__qianshi-put:::"..n)
      if #cards > 0 then
        table.reverse(cards)
        room:moveCards({
          ids = cards,
          from = player.id,
          toArea = Card.DrawPile,
          moveReason = fk.ReasonPut,
          skillName = self.name,
          proposer = player.id,
          moveVisible = false,
        })
      else
        room:invalidateSkill(player, self.name, "-turn")
      end
    end
  end,
}
luxun:addSkill(qianshi)

local zhuying = fk.CreateViewAsSkill{
  name = "rfenghou__zhuying",
  mute = true,
  switch_skill_name = "rfenghou__zhuying",
  prompt = function(self)
    return "#rfenghou__zhuying-"..Self:getSwitchSkillState(self.name, false, true)
  end,
  card_filter = Util.FalseFunc,
  view_as = function(self, cards)
    local card
    if Self:getSwitchSkillState(self.name, false) == fk.SwitchYang then
      card = Fk:cloneCard("fire_attack")
    else
      card = Fk:cloneCard("ex_nihilo")
    end
    card.skillName = self.name
    return card
  end,
  before_use = function (self, player, use)
    local room = player.room
    if player:getSwitchSkillState(self.name, true) == fk.SwitchYang then
      player:broadcastSkillInvoke(self.name, table.random({1, 2}))
      room:notifySkillInvoked(player, self.name, "offensive")
      player:drawCards(1, self.name)
    else
      player:broadcastSkillInvoke(self.name, table.random({3, 4}))
      room:notifySkillInvoked(player, self.name, "drawcard")
      player:throwAllCards("h")
    end
  end,
  enabled_at_play = function(self, player)
    if player:getSwitchSkillState(self.name, false) == fk.SwitchYang then
      return not table.find(Fk:currentRoom().alive_players, function (p)
        return p ~= player and p:getHandcardNum() == player:getHandcardNum()
      end)
    else
      return player:getHandcardNum() == 1 and not player:prohibitDiscard(player:getCardIds("h")[1])
    end
  end,
}
luxun:addSkill(zhuying)

Fk:loadTranslationTable{
  ["rfenghou__hell_luxun"] = "陆逊",
  ["#rfenghou__hell_luxun"] = "",
  ["illustrator:rfenghou__hell_luxun"] = "鬼画符",
  ["designer:rfenghou__hell_luxun"] = "屑",

  ["rfenghou__qianshi"] = "堑势",
  [":rfenghou__qianshi"] = "当你弃置你的牌时，你可以防止此次移动，改为重铸等量张牌，然后你可以使用一张【杀】。若你未使用【杀】或此【杀】"..
  "未造成伤害，你选择一项：1.将等量张牌置于牌堆顶；2.此技能本回合失效。",
  ["#rfenghou__qianshi-invoke"] = "堑势：你即将弃置%arg张牌，是否改为选择等量的牌重铸？",
  ["#rfenghou__qianshi-slash"] = "堑势：请使用一张【杀】，若不使用或此【杀】未造成伤害，你需将牌置于牌堆顶或令此技能本回合失效",
  ["#rfenghou__qianshi-put"] = "堑势：请将%arg张牌置于牌堆顶（先选择的置于上方，后选择的置于下方），或点“取消”令此技能本回合失效",

  ["rfenghou__zhuying"] = "烛营",
  [":rfenghou__zhuying"] = "转换技，阳：若你的手牌数唯一，你可以摸一张牌，视为使用【火攻】；阴：若你的手牌数为1，"..
  "你可以弃置此牌，视为使用【无中生有】。",
  ["#rfenghou__zhuying-yang"] = "烛营：你可以摸一张牌，视为使用【火攻】",
  ["#rfenghou__zhuying-yin"] = "烛营：你可以弃置唯一的手牌，视为使用【无中生有】",

  ["$rfenghou__qianshi1"] = "儒道尚仁而有礼，贤者知名而独悟。",
  ["$rfenghou__qianshi2"] = "儒门有言，仁为己任，此生不负孔孟之礼。",
  ["$rfenghou__zhuying1"]  = "明公彀中藏龙卧虎，放之海内皆可称贤。",
  ["$rfenghou__zhuying2"]  = "步步为营者，定无后顾之虞。",
  ["$rfenghou__zhuying3"] = "今提墨笔绘乾坤，湖海添色山永春。",
  ["$rfenghou__zhuying4"] = "手提玉剑斥千军，昔日锦鲤化金龙。",
}

local bigwestking = General:new(extension, "rfenghou__hell_zhangxianzhong", "west", 4)
--bigwestking.hidden = true

local rfenghou_hell__huangwu = fk.CreateTriggerSkill{
  name = "rfenghou_hell__huangwu",
  events = {fk.GameStart, fk.AfterDrawNCards, fk.TurnEnd},
  anim_type = "drawcard",
  derived_piles = "star",
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return false end
    if event == fk.TurnEnd then
      local mark = player:getMark("rfenghou_hell__huangwu-turn")
      return type(mark) == "string" and #table.filter(player:getPile("star"), function (id)
        return Fk:getCardById(id).trueName == "slash"
      end) > tonumber(mark)
    else
      return event == fk.GameStart or
      (target == player and not player:isKongcheng() and #player:getPile("star") > 0)
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event ~= fk.AfterDrawNCards then return true end
    return player.room:askForSkillInvoke(player, self.name, data, "#rfenghou_hell__huangwu-exchange")
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TurnEnd then
      local tos = room:askForChoosePlayers(player, table.map(room.alive_players, Util.IdMapper), 1, 1,
      "#rfenghou_hell__huangwu-damage", self.name, false)
      room:damage { from = player, to = room:getPlayerById(tos[1]), damage = 1, skillName = self.name, damageType = fk.FireDamage }
    else
      if event == fk.GameStart then
        player:addToPile("star", room:getNCards(7), true, self.name)
        if player.dead or player:isKongcheng() or #player:getPile("star") == 0 then return false end
      end
      local cids = room:askForArrangeCards(player, self.name,
      {player:getPile("star"), player:getCardIds(Player.Hand), "star", "$Hand"}, "#rfenghou_hell__huangwu-exchange", true)
      U.swapCardsWithPile(player, cids[1], cids[2], self.name, "star", true, player.id)
    end
  end,

  refresh_events = {fk.TurnStart},
  can_refresh = function (self, event, target, player, data)
    return player:hasSkill(self, true)
  end,
  on_refresh = function (self, event, target, player, data)
    player.room:setPlayerMark(player, "rfenghou_hell__huangwu-turn", tostring(#table.filter(player:getPile("star"), function (id)
      return Fk:getCardById(id).trueName == "slash"
    end)))
  end,
}

bigwestking:addSkill(rfenghou_hell__huangwu)

local rfenghou_hell__huabian = fk.CreateTriggerSkill{
  name = "rfenghou_hell__huabian",
  events = {fk.EventPhaseStart, fk.AfterCardsMove},
  anim_type = "offensive",
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return false end
    if event == fk.EventPhaseStart then
      return target.phase == Player.Play and #player:getPile("star") > 0
    elseif player:hasSkill(self) and player:usedSkillTimes(self.name, Player.HistoryTurn) > 0 then
      local e = player.room.logic:getCurrentEvent().parent
      if e and e.event == GameEvent.Death then
        local cards = {}
        for _, move in ipairs(data) do
          if move.moveReason == fk.ReasonDiscard and move.skillName == "" 
          and move.from and player.room:getPlayerById(move.from).dead then
            for _, info in ipairs(move.moveInfo) do
              table.insertIfNeed(cards, info.cardId)
            end
          end
        end
        if #cards > 0 then
          self.cost_data = {cards = cards}
          return true
        end
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.AfterCardsMove then return true end
    local use = U.askForUseRealCard(player.room, player, player:getPile("star"), ".", self.name,
    "#rfenghou_hell__huabian-invoke:"..target.id, {expand_pile = "star", bypass_distances = true}, true, true)
    if use then
      self.cost_data = {tos = {target.id}, skill_info = use}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseStart then
      room:useCard(self.cost_data.skill_info)
      while not player.dead and #player:getPile("star") > 0 do
        if not U.askForUseRealCard(player.room, player, player:getPile("star"), ".", self.name,
        "#rfenghou_hell__huabian-use", {expand_pile = "star", bypass_distances = true}) then break end
      end
      if not player.dead and not target.dead then
        local choice = room:askForChoice(player, {"rfenghou_hell__huabian_draw:"..target.id,
        "rfenghou_hell__huabian_discard:"..target.id}, self.name)
        if choice:startsWith("rfenghou_hell__huabian_draw") then
          target:drawCards(2, self.name)
        elseif not target:isNude() then
          room:askForDiscard(target, 2, 2, true, self.name, false)
        end
      end
    else
      player:addToPile("star", self.cost_data.cards, true, self.name)
    end
  end,
}
bigwestking:addSkill(rfenghou_hell__huabian)

bigwestking:addRelatedSkill("qixing")

Fk:loadTranslationTable{
  ["rfenghou__hell_zhangxianzhong"] = "张献忠",
  ["#rfenghou__hell_zhangxianzhong"] = "浮命髏川",
  ["designer:rfenghou__hell_zhangxianzhong"] = "拼音",
  ["illustrator:rfenghou__hell_zhangxianzhong"] = "",

  ["rfenghou_hell__huangwu"] = "荒武",
  [":rfenghou_hell__huangwu"] = "锁定技，你视为拥有“七星”，你的“星”明置。“星”中的【杀】比回合开始时多的回合结束时，你对一名角色造成1点火焰伤害。",
  ["#rfenghou_hell__huangwu-exchange"] = "荒武：你可以交换任意张“星”牌与手牌",
  ["#rfenghou_hell__huangwu-damage"] = "荒武：选择一名角色，你对其造成1点火焰伤害",

  ["rfenghou_hell__huabian"] = "猾变",
  [":rfenghou_hell__huabian"] = "一名角色的出牌阶段开始时，你可无视距离使用至少一张“星”，令其摸或弃两张牌；发动过“猾变”的回合内，你将已死亡角色的弃牌置入“星”中。",
  ["#rfenghou_hell__huabian-use"] = "猾变：你可以再使用“星”牌！",
  ["#rfenghou_hell__huabian-invoke"] = "猾变：你可以使用一张“星”，然后令 %src 摸或弃两张牌",
  ["rfenghou_hell__huabian_discard"] = "令 %src 弃两张牌",
  ["rfenghou_hell__huabian_draw"] = "令 %src 摸两张牌",
}










local shibing = General:new(extension, "rfenghou__shibing", "qun", 5)
shibing.hidden = true

local rfenghou__chuzhan = fk.CreateTriggerSkill{
  name = "rfenghou__chuzhan",
  events = {fk.GamePrepared},
  priority = 1.01,
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self)
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local generalNum = room.settings.generalNum
    local generals = room:getNGenerals(generalNum)
    local general = room:askForGeneral(player, generals, 1)---@type string
    room:returnToGeneralPile(generals)
    room:changeHero(player, general, false, false, false, true, true)
    room:setPlayerProperty(player, "hp", Fk.generals[general].hp)
    -- 无法进入隐匿……
  end,
}
shibing:addSkill(rfenghou__chuzhan)

Fk:loadTranslationTable{
  ["rfenghou__shibing"] = "士兵",
  ["#rfenghou__shibing"] = "",
  ["illustrator:rfenghou__shibing"] = "",
  ["designer:rfenghou__shibing"] = "",

  ["rfenghou__chuzhan"] = "出战",
  [":rfenghou__chuzhan"] = "游戏开始前，你重新选将。",
}



return extension
